<script setup>
import { forEach, map, merge, pick } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import { basicTitle, basicLineXAxis, basicLineYAxis, basicLineLegend } from '@/components/chart/options/baseOptions.js';
import { getOrderData } from '@/api/index.js';
import CECharts from '@/components/chart/CECharts.vue';

const props = defineProps({
  month: { type: String | null, default: () => null },
  data: { type: Object | null, default: () => null },
  params: { type: Object | null, default: () => null },
});
const headerStyle = { backgroundColor: '#d2e4e5', color: '#606266' };
const baseCommColumns = [
  { prop: 'energyType', label: '能源类型' },
  { prop: 'energyBasisValue', label: '基准能耗' },
  { prop: 'energyConsumeValue', label: '实际能耗' },
  { prop: 'energyConservationValue', label: '节能量' },
  { prop: 'energyConservationValueRatio', label: '节能率(%)' },
];
const commonColumns = [
  ...baseCommColumns,
  { prop: 'substructTco', label: '减排量(tco2)' },
  { prop: 'energyBasisCost', label: '基准费用(元)' },
  { prop: 'energyConsumeCost', label: '实际费用(元)' },
];
const monColumnObj = ref({
  CONVENTION: [...commonColumns, { prop: 'energyEarningsConservationCost', label: '节能收益(元)' }],
  SHARE: [
    ...commonColumns,
    { prop: 'energyConservationCost', label: '节能总收益(元)' },
    { prop: 'energyEarningsConservationRatio', label: '综能收益占比(%)' },
    { prop: 'energyEarningsConservationCost', label: '综能能耗节能收益(元)' },
  ],
  ENSURE: [
    ...baseCommColumns,
    { prop: 'energyGuaranteeConservationValue', label: '保证节能量/节能率(%)' },
    { prop: 'energyConservationValueGap', label: '节能量差值' },
    { prop: 'substructTco', label: '减排量(tco2)' },
    { prop: 'energyBasisCost', label: '标准服务费(元)' },
    { prop: 'energyEarningsConservationCost', label: '实际项目收益(元)' },
  ],
});
const getSpecLabel = (item, type) => {
  const engCostLabel = {
    CONVENTION: '项目收益(元)',
    SHARE: '综能项目收益(元)',
    ENSURE: '实际项目收益(元)',
  };
  return (
    {
      energyType: '合计',
      energyBasisValue: '基准能耗(tce)',
      energyConsumeValue: '实际能耗(tce)',
      energyConservationValue: '节能量(tce)',
      energyEarningsConservationCost: engCostLabel[type],
    }[item.prop] ?? item.label
  );
};
const dayColumnObj = ref({
  CONVENTION: [
    { prop: 'energyValueDate', label: '统计时间', width: 100 },
    { prop: 'energyType', label: '能源类型', width: 100 },
    { prop: 'energyBasisValue', label: '基准能耗' },
    { prop: 'energyConsumeValue', label: '实际能耗' },
    { prop: 'energyConservationValue', label: '节能量' },
    { prop: 'energyConservationValueRatio', label: '节能率(%)' },
    { prop: 'energyBasisCost', label: '基准费用(元)' },
    { prop: 'energyConsumeCost', label: '实际费用(元)' },
    { prop: 'energyEarningsConservationCost', label: '节能收益(元)' },
  ],
  SHARE: [
    { prop: 'energyValueDate', label: '统计时间', width: 100 },
    { prop: 'energyType', label: '能源类型', width: 100 },
    { prop: 'energyBasisValue', label: '基准能耗' },
    { prop: 'energyConsumeValue', label: '实际能耗' },
    { prop: 'energyConservationValue', label: '节能量' },
    { prop: 'energyBasisCost', label: '基准费用(元)' },
    { prop: 'energyConsumeCost', label: '实际费用(元)' },
    { prop: 'energyConservationCost', label: '节能总收益(元)' },
    { prop: 'energyEarningsConservationRatio', label: '综能收益占比(%)' },
    { prop: 'energyEarningsConservationCost', label: '综能能耗节能收益(元)' },
  ],
  ENSURE: [
    { prop: 'energyValueDate', label: '统计时间', width: 100 },
    { prop: 'energyType', label: '能源类型', width: 100 },
    { prop: 'energyBasisValue', label: '基准能耗' },
    { prop: 'energyConsumeValue', label: '实际能耗' },
    { prop: 'energyConservationValue', label: '节能量' },
    { prop: 'energyConservationValueRatio', label: '节能率(%)' },
    { prop: 'energyGuaranteeConservationValue', label: '保证节能量/节能率(%)' },
    { prop: 'energyConservationValueGap', label: '节能量/率差值' },
  ],
});
const chartRef = ref(null);
const textStyle = {
  color: '#303133',
  fontWeight: 'normal',
  fontSize: 14,
  lineHeight: 16,
};
const commonOpts = {
  title: [
    merge({}, basicTitle, {
      text: '节能分析',
      top: 0,
      textStyle,
    }),
    merge({}, basicTitle, {
      text: '收益分析',
      textStyle,
      top: '50%',
    }),
  ],
  tooltip: {
    formatter: params => {
      if (Array.isArray(params) && params.length > 0) {
        let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
        forEach(params, e => {
          let seriesName = e.seriesName;
          let value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
          str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
        });
        return str;
      }
      return '';
    },
  },
  axisPointer: {
    link: { xAxisIndex: 'all' },
  },
  color: ['#26d5d5', '#4992ff', '#eda422', '#f53019', '#5afe5d', '#f58819', '#fe5a5a', '#d5d526'],
  dataZoom: null,
};
const setChartOpt = (type, unit) => {
  const axisObj = {
    xAxis: [merge({}, basicLineXAxis, { gridIndex: 0 }), merge({}, basicLineXAxis, { gridIndex: 1 })],
    yAxis: [
      merge({}, basicLineYAxis, {
        name: `单位：${unit}`,
        nameTextStyle: { fontSize: 12 },
        gridIndex: 0,
      }),
      merge({}, basicLineYAxis, {
        name: `单位：${type !== 'ENSURE' ? '元' : unit}`,
        nameTextStyle: { fontSize: 12 },
        gridIndex: 1,
      }),
    ],
  };
  return {
    CONVENTION: {
      legend: [
        merge({}, basicLineLegend, {
          data: ['基准能耗', '实际能耗'],
          x: 'center',
          y: 15,
        }),
        merge({}, basicLineLegend, {
          data: ['基准费用', '实际费用'],
          x: 'center',
          y: '55%',
        }),
      ],
      grid: [
        { bottom: 20, top: 50, left: 60, right: 10, height: '28%' },
        { bottom: 0, top: '65%', left: 60, right: 10, height: '28%' },
      ],
      ...axisObj,
    },
    SHARE: {
      title: [{}, { top: '35.5%' }],
      legend: [
        merge({}, basicLineLegend, {
          data: ['基准能耗', '实际能耗'],
          x: 'center',
          y: 15,
        }),
        merge({}, basicLineLegend, {
          data: ['基准费用', '实际费用'],
          x: 'center',
          y: '40%',
        }),
        merge({}, basicLineLegend, {
          data: ['节能总收益', '综能能耗节能收益'],
          x: 'center',
          y: '70%',
        }),
      ],
      grid: [
        { bottom: 0, top: 50, left: 60, right: 10, height: '16%' },
        { bottom: 0, top: '48%', left: 60, right: 10, height: '16%' },
        { bottom: 0, top: '78%', left: 60, right: 10, height: '16%' },
      ],
      xAxis: [
        merge({}, basicLineXAxis, { gridIndex: 0 }),
        merge({}, basicLineXAxis, { gridIndex: 1 }),
        merge({}, basicLineXAxis, { gridIndex: 2 }),
      ],
      yAxis: [
        merge({}, basicLineYAxis, {
          name: `单位：${unit}`,
          nameTextStyle: { fontSize: 12 },
          gridIndex: 0,
        }),
        merge({}, basicLineYAxis, {
          name: `单位：元`,
          nameTextStyle: { fontSize: 12 },
          gridIndex: 1,
        }),
        merge({}, basicLineYAxis, {
          name: `单位：元`,
          nameTextStyle: { fontSize: 12 },
          gridIndex: 2,
        }),
      ],
    },
    ENSURE: {
      title: [{}, { show: false }],
      legend: [
        merge({}, basicLineLegend, {
          data: ['基准能耗', '实际能耗'],
          x: 'center',
          y: 15,
        }),
        merge({}, basicLineLegend, {
          data: ['保证节能量', '实际节能量', '节能量差值'],
          x: 'center',
          y: '55%',
        }),
      ],
      grid: [
        { bottom: 20, top: 50, left: 60, right: 10, height: '28%' },
        { bottom: 0, top: '65%', left: 60, right: 10, height: '28%' },
      ],
      ...axisObj,
    },
  }[type];
};
const getDatasetByType = (type, data) => {
  return {
    CONVENTION: [
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
        ],
        source: data,
      },
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '基准费用' },
          { name: 'energyConsumeCost', displayName: '实际费用' },
        ],
        source: data,
      },
    ],
    SHARE: [
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
        ],
        source: data,
      },
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '基准费用' },
          { name: 'energyConsumeCost', displayName: '实际费用' },
        ],
        source: data,
      },
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyConservationCost', displayName: '节能总收益' },
          { name: 'energyEarningsConservationCost', displayName: '综能能耗节能收益' },
        ],
        source: data,
      },
    ],
    ENSURE: [
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
        ],
        source: data,
      },
      {
        dimensions: [
          'energyValueDate',
          { name: 'energyGuaranteeConservationValue', displayName: '保证节能量' },
          { name: 'energyConservationValue', displayName: '实际节能量' },
          { name: 'energyConservationValueGap', displayName: '节能量差值' },
        ],
        source: data,
      },
    ],
  }[type];
};
const getSeriesByType = type => {
  const lineObj = {
    type: 'line',
    smooth: true,
    showSymbol: false,
    lineStyle: { type: 'dashed' },
  };
  const barObj = { type: 'bar', barWidth: 12 };
  return {
    CONVENTION: [
      { ...lineObj, datasetIndex: 0, xAxisIndex: 0, yAxisIndex: 0 },
      { ...barObj, datasetIndex: 0, xAxisIndex: 0, yAxisIndex: 0 },
      { ...lineObj, datasetIndex: 1, xAxisIndex: 1, yAxisIndex: 1 },
      { ...barObj, datasetIndex: 1, xAxisIndex: 1, yAxisIndex: 1 },
    ],
    SHARE: [
      { ...lineObj, datasetIndex: 0, xAxisIndex: 0, yAxisIndex: 0 },
      { ...barObj, datasetIndex: 0, xAxisIndex: 0, yAxisIndex: 0 },
      { ...lineObj, datasetIndex: 1, xAxisIndex: 1, yAxisIndex: 1 },
      { ...barObj, datasetIndex: 1, xAxisIndex: 1, yAxisIndex: 1 },
      { ...barObj, datasetIndex: 2, xAxisIndex: 2, yAxisIndex: 2 },
      { ...barObj, barGap: '-100%', datasetIndex: 2, xAxisIndex: 2, yAxisIndex: 2 },
    ],
    ENSURE: [
      { ...lineObj, datasetIndex: 0, xAxisIndex: 0, yAxisIndex: 0 },
      { ...barObj, datasetIndex: 0, xAxisIndex: 0, yAxisIndex: 0 },
      { ...lineObj, datasetIndex: 1, xAxisIndex: 1, yAxisIndex: 1 },
      { ...barObj, datasetIndex: 1, xAxisIndex: 1, yAxisIndex: 1 },
      merge({}, lineObj, {
        lineStyle: { type: 'solid' },
        datasetIndex: 1,
        xAxisIndex: 1,
        yAxisIndex: 1,
      }),
    ],
  }[type];
};
const tgChartOpts = (type, data, unit) => {
  let optsObj = {};
  optsObj = setChartOpt(type, unit);
  optsObj.dataset = getDatasetByType(type, data);
  optsObj.series = getSeriesByType(type);
  return merge({}, commonOpts, optsObj);
};
const orderList = [
  { label: '报修设备编号', key: 'equCode' },
  { label: '报修设备名称', key: 'equName' },
  { label: '故障原因', key: 'reason' },
  { label: '工单状态', key: 'workOrderStatus' },
  { label: '处理人', key: 'handlePeople' },
  { label: '处理结果', key: 'handleResult' },
  { label: '处理时间', key: 'handleTime' },
  { label: '机构编号', key: 'institutionCode' },
  { label: '机构名称', key: 'buildingName' },
];
const [orderData, , runOrder] = useRequest(getOrderData, { manual: true });

useWatch(
  () => props.params,
  n => {
    const commParams = pick(n, ['buildingCodes', 'dateStart', 'projectType']);
    runOrder({ ...commParams });
  },
  { immediate: true, deep: true },
);

const getChartImgs = () => {
  const imgOpt = {
    type: 'jpeg',
    pixelRatio: 1,
    backgroundColor: '#fff',
  };
  return map(chartRef.value, v => v.$$chart.getDataURL(imgOpt).replace('data:image/jpeg;base64,', ''));
};
defineExpose({ getChartImgs });
</script>

<template>
  <div class="rep-wrapper rep-content" style="padding-bottom: 20px">
    <div class="rep-content-title">一、总览</div>
    <div class="rep-content-text">
      <span>{{ month ? dayjs(month).format('YYYY年M月') : '-年-月' }}</span>
      报告，托管（{{ data?.buildName ?? '-' }}）{{ data?.count ?? '--' }}家机构，总计能耗
      <span>{{ data?.sumEnergy ?? '--' }}</span>
      tce，总计节能量
      <span>{{ data?.sumConservation ?? '--' }}</span>
      tce，减少碳排
      <span>{{ data?.sumDioxide ?? '--' }}</span>
      tco2，能源能耗总费用
      <span>{{ data?.sumAmount ?? '--' }}</span>
      元，项目总收益
      <span>{{ data?.sumConservationEarnings ?? '--' }}</span>
      元。
    </div>
    <div class="rep-content-title">二、托管机构数据分析</div>
    <div v-for="(item, idx) in data?.listsInstitutionResults ?? []" :key="item.name + idx" class="rep-contList">
      <div class="rep-content-subtitle">2.{{ idx + 1 }} {{ item?.name ?? '--' }}机构数据分析</div>
      <div class="rep-content-subtitle">2.{{ idx + 1 }}.1 机构项目合同能源管理类型</div>
      <table class="tgTable rep-content-totalTable">
        <tr>
          <th>机构代码</th>
          <th>机构名称</th>
          <th>项目合同能源管理类型</th>
        </tr>
        <tr>
          <td>{{ item?.institutionCode ?? '-' }}</td>
          <td>{{ item?.name ?? '-' }}</td>
          <td>{{ item?.agrementType ?? '-' }}</td>
        </tr>
      </table>
      <div class="rep-content-subtitle">2.{{ idx + 1 }}.2 节能、收益统计</div>
      <el-table :data="item?.totalTypeEnergys ?? []" :header-cell-style="headerStyle" class="tgMonTable">
        <el-table-column
          v-for="columnItem in monColumnObj[item?.agrementTypeName] ?? []"
          :key="columnItem.prop"
          :prop="columnItem.prop"
          :label="getSpecLabel(columnItem, item.agrementTypeName)"
          align="center"
        />
      </el-table>
      <el-table :data="item?.typeEnergys ?? []" :header-cell-style="headerStyle" class="tgMonTable">
        <el-table-column
          v-for="columnItem in monColumnObj[item?.agrementTypeName] ?? []"
          :key="columnItem.prop"
          :prop="columnItem.prop"
          :label="columnItem.label"
          align="center"
        />
      </el-table>
      <div class="rep-content-subtitle">
        2.{{ idx + 1 }}.3 分项能源能耗节能{{ item?.agrementTypeName === 'CONVENTION' ? '、收益' : '' }}分析
      </div>
      <template v-for="(engsItem, engsIdx) in item?.energys">
        <div class="rep-content-subtitle" :key="engsItem?.energyType + engsIdx">
          2.{{ idx + 1 }}.3.{{ engsIdx + 1 }} 用{{ engsItem?.energyType ?? '-' }}能耗节能{{
            item?.agrementTypeName === 'CONVENTION' ? '、收益' : ''
          }}分析
        </div>
        <CECharts
          ref="chartRef"
          type="line"
          class="chart-box"
          :options="tgChartOpts(item?.agrementTypeName, engsItem?.dataList ?? [], engsItem?.energyUnit)"
        />
        <el-table :data="engsItem?.dataList ?? []" :header-cell-style="headerStyle">
          <el-table-column
            v-for="dColumnItem in dayColumnObj[item?.agrementTypeName] ?? []"
            :key="dColumnItem.prop"
            :prop="dColumnItem.prop"
            :label="dColumnItem.label"
            :width="dColumnItem?.width"
            align="center"
          />
        </el-table>
      </template>
    </div>
    <div class="rep-content-title">三、告警统计</div>
    <div class="rep-content-subtitle">3.1 能耗告警统计</div>
    <el-table :data="data?.energyAlarm ?? []" :header-cell-style="headerStyle">
      <el-table-column prop="startTime" label="统计时间" width="100" align="center" />
      <el-table-column prop="energyTypeInfo" label="能耗类型" width="100" align="center" />
      <el-table-column prop="dataDate" label="超标时间" align="center" />
      <el-table-column prop="energyValue" label="实际能耗" align="center" />
      <el-table-column prop="checkType" label="超出考核类型" align="center" />
      <el-table-column prop="energyExceeding" label="超标量" align="center" />
      <el-table-column prop="enterpriseCode" label="机构编号" align="center" />
      <el-table-column prop="enterpriseName" label="机构名称" align="center" />
    </el-table>
    <div class="rep-content-subtitle">3.2 设备告警统计</div>
    <el-table :data="data?.facilityAlarm ?? []" :header-cell-style="headerStyle">
      <el-table-column prop="startTime" label="统计时间" width="100" align="center"></el-table-column>
      <el-table-column prop="equCode" label="设备编号" width="100" align="center"></el-table-column>
      <el-table-column prop="equName" label="设备名称" align="center"></el-table-column>
      <el-table-column prop="alarmReason" label="告警描述" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="enterpriseCode" label="机构编号" align="center"></el-table-column>
      <el-table-column prop="enterpriseName" label="机构名称" align="center"></el-table-column>
    </el-table>
    <div class="rep-content-title">四、设备维修工单统计</div>
    <div v-for="orderItem in orderData" :key="orderItem?.workOrderCode" class="u-mb20">
      <div class="u-df-spb u-fs14 u-mb5">
        <div class="u-fw-b" style="color: #303133">{{ orderItem?.workOrderCode }}</div>
        <div style="color: #909399">{{ orderItem?.startTime }}</div>
      </div>
      <el-descriptions title="" :column="3" size="small" border>
        <el-descriptions-item
          v-for="(item, index) in orderList"
          :key="index"
          :labelStyle="{
            color: '#606266',
            textAlign: 'left !important',
            backgroundColor: '#d2e4e5',
          }"
          :contentStyle="{
            color: '#606266',
            textAlign: 'left !important',
            backgroundColor: '#fff',
          }"
        >
          <template slot="label">
            <div class="u-df-st">
              <div class="info-descriptionsItem">{{ item.label }}</div>
            </div>
          </template>
          <div class="info-descriptionsItem">{{ orderItem?.[item.key] ?? '--' }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div v-show="orderData?.length <= 0" class="text-center u-fs14" style="color: #909399">暂无数据</div>
  </div>
</template>

<style lang="scss" scoped>
.tgTable.rep-content-totalTable {
  th {
    border-right: 1px solid transparent;
  }
  tr td {
    border-right: 1px solid transparent;
  }
  tr > td:first-of-type {
    background-color: unset;
  }
}
.rep-titleMark {
  width: 4px;
  height: 18px;
  margin-right: 5px;
  background-color: #1e787c;
}
.chart-box {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}
.info-descriptionsItem {
  height: 18px;
  line-height: 18px;
  margin-left: 6px;
}
.tgMonTable .el-table__body::-webkit-scrollbar-thumb {
  background: #ebeef5 !important;
}
:deep(.el-table--border) {
  border: none;
}
:deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  background-color: #fff;
}
:deep(.el-table td) {
  background-color: #fff;
}
:deep(.el-table tr) {
  background-color: #fff;
}
:deep(.el-table__cell) {
  color: #606266 !important;
}
:deep(.el-table td.el-table__cell) {
  border-bottom: 1px solid #ebeef5 !important;
}
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #ebeef5 !important;
}
:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}
:deep(.el-descriptions .is-bordered .el-descriptions-item__cell) {
  border-color: #d4d4d4;
}
</style>
